package com.ivan.stu.notetool.utils;

import android.text.TextUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by IVAN on 2018/11/12.
 */

public class EncryptUtil {


    /**
     * 加密算法
     *
     * @throws UnsupportedEncodingException
     * @return加密后字符串
     */
    public static   String EncryptCode(String userID, String str) {
        byte[] idByte = null;
        try {
            idByte = md5(userID).getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte S_key = idByte[idByte.length - 1];// 密钥
        byte[] value;
        try {
            value = str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            value = str.getBytes();
        }
        int[] valueXOR = new int[value.length];// 异或之后的字符串
        StringBuffer result = new StringBuffer("");// 结果字符串
        for (int i = 0; i < value.length; i++) {
            // value[i]与S_key异或运算
            // Log.i("加密", "异或之后 " + (value[i] ^ S_key));
            valueXOR[i] = (value[i] ^ S_key);
            if (valueXOR[i] < 0) {
                valueXOR[i] += 256;
            }
            result.append(String.format("%03d", valueXOR[i]));// 左侧补充0
        }
        String finalResult = result.reverse().toString();
        return finalResult;
    }

    public static    String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}
